/**
 * FileName: ClientV0
 * Author:   powersi
 * Date:     2021/2/26 10:12
 * Description:
 */
package com.zm.demo.netty.action.client;

import com.zm.demo.netty.action.client.codec.OrderFrameDecoder;
import com.zm.demo.netty.action.client.codec.OrderFrameEncoder;
import com.zm.demo.netty.action.client.codec.OrderProtocolDecoder;
import com.zm.demo.netty.action.client.codec.OrderProtocolEncoder;
import com.zm.demo.netty.action.common.RequestMessage;
import com.zm.demo.netty.action.common.order.OrderOperation;
import com.zm.demo.netty.action.util.IdUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Description: 
 * Author:      powersi
 * Date:        2021/2/26 10:12
 */
public class ClientV0 {


    public static void main(String[] args) {


        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);

        NioEventLoopGroup group = new NioEventLoopGroup();

        bootstrap.handler(new LoggingHandler(LogLevel.INFO));
        bootstrap.group(group);
        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                ch.pipeline().addLast(new OrderFrameEncoder());
                ch.pipeline().addLast(new OrderFrameDecoder());
                ch.pipeline().addLast(new OrderProtocolEncoder());
                ch.pipeline().addLast(new OrderProtocolDecoder());
                ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
            }
        });

        try {
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8090).sync();
            channelFuture.sync();

            RequestMessage requestMessage =new RequestMessage(IdUtil.nextId(), new OrderOperation(1001, "tudou"));
            channelFuture.channel().writeAndFlush(requestMessage);


            channelFuture.channel().closeFuture().sync();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
